package com.lostreseditores.sabersai.utilities;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import com.lostreseditores.sabersai.model.Colegio;
import com.lostreseditores.sabersai.model.Lugar;
import com.lostreseditores.sabersai.presentation.businessDelegate.BusinessDelegatorView;

public class ColegioLazyList extends LazyDataModel<Colegio> {

	private static final long serialVersionUID = 1L;

	private List<Colegio> colegios = new ArrayList<Colegio>();

	public List<Colegio> load(int startingAt, int maxPerPage, String sortField,
			SortOrder sortOrder, Map<String, String> filters) {

		String order;

		/*System.out.println("maxPerPage (ColegioLazyList): "+ maxPerPage);
		System.out.println("colecoddanen (ColegioLazyList): " + filters.get("colecoddanen"));
		System.out.println("coledescripv (ColegioLazyList): " + filters.get("coledescripv"));*/

		String lugaidn = null;

		if (FacesUtils.getSession().getAttribute("lugaidn") != null) {
			lugaidn = FacesUtils.getSession().getAttribute("lugaidn")
					.toString();
		}

		if (sortOrder.toString().equals("ASCENDING")) {
			order = "asc";
		} else {
			order = "desc";
		}

		if (sortField == null) {
			sortField = "colecoddanen";
		}

		// with datatable pagination limits
		try {
			colegios = BusinessDelegatorView.encontrarColegios(startingAt,
					maxPerPage, order, sortField, filters, lugaidn);

			for (int i = 0; i < colegios.size(); i++) {
				Lugar l = BusinessDelegatorView.obtenerLugarPorCodigo(
						colegios.get(i).getLugaidn()).get(0);
				colegios.get(i).setLugadescripv(l.getLugadescripv());
			}

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		Long p = null;

		try {
			p = BusinessDelegatorView.findTotalNumberColegio(filters, lugaidn);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		setRowCount(Integer.parseInt(p + ""));

		// set the page size
		setPageSize(maxPerPage);
		return colegios;
	}

	public Object getRowKey(Colegio colegio) {
		return colegio.getColecoddanen();
	}

	public Colegio getRowData(String colegioDane) {
		Integer id = Integer.valueOf(colegioDane);

		for (Colegio colegio : colegios) {
			if (id.equals(colegio.getColecoddanen())) {
				return colegio;
			}
		}
		return null;
	}
}
